﻿using System;
using System.Windows;
using SilverlightUtils;
using StoryDesigner.Webservices;

namespace StoryDesigner
{
	public partial class LoginScreen
	{
		public LoginScreen()
		{
			// Required to initialize variables
			InitializeComponent();
			App.Client.ServerErrorReceived += ClientServerErrorReceived;
		    //_captureSource = captureSource;
		}

		private static void ClientServerErrorReceived(object sender, ServerErrorReceivedEventArgs e)
		{
			MessageBox.Show(string.Format("{0}: {1}", e.Severity, e.Message), e.Severity.ToString(), MessageBoxButton.OK);
		}

		private void BtnLoginOkClick(object sender, RoutedEventArgs e)
		{
			btnLoginOK.IsEnabled = false;
			if (txtLogin.Text == string.Empty || txtPassword.Password == string.Empty)
			{
				MessageBox.Show("Error: You must provide both username and password.");
				btnLoginOK.IsEnabled = true;
				return;
			}
			VisualStateManager.GoToState(this, "Busy", true);

			App.Client.LoginCompleted += ClientLoginCompleted;
			App.Client.LoginAsync(txtLogin.Text, txtPassword.Password.EncryptPassword());
		}

		private void ClientLoginCompleted(object sender, LoginCompletedEventArgs e)
		{
			App.Client.LoginCompleted -= ClientLoginCompleted;
			if (e.Error != null) { App.ServerError(); return; }
			if (e.Result != null)
			{
				App.InternalSessionId = e.Result.SessionId;
				//App.MyGatewayId = e.Result.GatewayId;
				//App.MyKnownComputers = e.Result.MyKnownComputers;
				//App.MyGatewayCpuSpeed = e.Result.TotalCpuSpeed;
				//App.MyGatewayTotalMemory = e.Result.TotalMemory;
				//App.MyGatewayBandwidth = e.Result.TotalBandwidth;
				//App.MySystemId = e.Result.SystemId;
				//App.MyCorporationId = e.Result.CorporationId;
				//App.MyRootDirectoryId = e.Result.RootDirectoryId;
				//App.Login = txtLogin.Text;
				//App.Password = txtPassword.Password.EncryptPassword();
				//App.MyIP = e.Result.IP;

				App.Client.ServerErrorReceived -= ClientServerErrorReceived;
				Content = new MainPage();
			}
			else
			{
				VisualStateManager.GoToState(this, "Normal", true);
			}
			btnLoginOK.IsEnabled = true;
		}
	}
}